<?php

namespace app\Modules\Api\controllers;



use Yii;
use app\Modules\Api\models\Saleorder;
use app\Modules\Api\models\Addr;
use app\filters\Json;
use app\helpers\Request;
use app\alipay\AopClient;
use app\alipay\request\AlipayTradeAppPayRequest;

/**
 * Class OrderController
 * @package app\Modules\Api\controllers
 */
class PayController extends ControllerBase
{

    public function actionPaysend($order_id)
    {
        //$order_id = Request::strictpost('order_id','缺少订单id');
        $order = Saleorder::findOne($order_id);
        if(!$order)
            return Json::error('订单不存在');
        $addr_id = Yii::$app->request->post('addr_id',0);

        $addr = Addr::findOne($addr_id);
        if(!$addr)
            return Json::error('未填写收货地址');

        $type = Yii::$app->request->post('type',Saleorder::PAY_ALIPAY);
        $remarks = Yii::$app->request->post('remarks','');
        $order->setAddr($addr);
        $order->setPaytype($type);
        $order->remarks = $remarks;
        $order->save(false);
        switch($order->pay_type)
        {
            case Saleorder::PAY_ALIPAY:
                $response = $this->getAlipay($order);
                $data = ['type'=>'1','excute'=>$response];
                break;
            case Saleorder::PAY_WX:
                $data = ['type'=>'2'];
                break;
            default:
                return Json::error('未知的支付方式');

        }
        return Json::success($data);
    }

    protected function getAlipay(Saleorder $order)
    {
        $aop = new AopClient;
        $params = Yii::$app->params['alipay'];
        $aop->appId = $params['appId'];
        $aop->rsaPrivateKey = $params['rsaPrivateKey'];
        $aop->format = $params['format'];
        // $aop->charset = Yii::$app->params['charset'];
        $aop->signType = $params['signType'];
        $aop->alipayrsaPublicKey = $params['alipayrsaPublicKey'];
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        $bizcontent = json_encode([
            'body'=>$order->pname,
            'subject'=>$order->pspec,
            'out_trade_no'=>$order->out_trade_no,//此订单号为商户唯一订单号
            'total_amount'=> $order->price,//保留两位小数
            'product_code'=>'QUICK_MSECURITY_PAY'
        ]);
        $request->setNotifyUrl("商户外网可以访问的异步地址");
        $request->setBizContent($bizcontent);
        //这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
        return $response;
    }

    public function actionAlipaynotify()
    {
        $this->html();
        $aop = new AopClient;
        $params = Yii::$app->params['alipay'];
        $aop->alipayrsaPublicKey = $params['alipayrsaPublicKey'];
        $post = Yii::$app->request->post();
        $flag = $aop->rsaCheckV1($post, NULL, "RSA");
        if($flag&&$post['trade_status'] == 'TRADE_SUCCESS'){
            $out_trade_no = $post['out_trade_no'];
            $order = Saleorder::find()->where(['out_trade_no'=>$out_trade_no])->one();
            $order->state = Saleorder::STEAT_PAID;
            $order->save(false);
            echo "success";
        }else{
            echo "fail";
        }
    }
    public function actionWxnotify()
    {
        $post = file_get_contents("php://input");
        file_put_contents("wxzf2.txt",serialize($post).PHP_EOL,FILE_APPEND);
        if(!empty($post)){
            echo "SUCCESS";
            $postObj = simplexml_load_string($post,'SimpleXMLElement', LIBXML_NOCDATA);
            $postObj = json_decode(json_encode($postObj),true);
        }else{
            return false;
        }
        $order = M('order')->where(array('onum'=>$postObj['out_trade_no']))->find();
        if($order){
            //如果订单存在就判断支付是否成功
            if($postObj['result_code'] == 'SUCCESS'){
                //更新订单状态
                $data['trade_no'] = $postObj['transaction_id'];
                $data['buyer_email'] = $postObj['openid'];
                $price = $postObj['total_fee'];
                $data['status'] = '2';
                $data['payfs'] = '1';
                M('order')->where(array('onum'=>$postObj['out_trade_no']))->save($data);
                $price = $price/10;
                if(strlen($postObj['out_trade_no']) == '13'){
                    //通过订单号长度判断该订单是否是充值是充值就按照1:10的比例更新该用户余额
                    M('member')->where(array('userid'=>$order['mid']))->setInc('money',$price);
                    //$this->sethistory('您微信充值',date('Y-m-d G:i:s',time()),$order['mid'],$price);
                    if(strlen(mysql_query()) > '0'){
                        //如果更新失败会写入记事本
                        file_put_contents("error.txt",date('Y-m-d H:i:s',time()).'用户充值更新余额失败，id'.$order['mid'].'金额'.$price.PHP_EOL,FILE_APPEND);
                    }
                }else{
                    $seller = M('member')->where(array('userid'=>$order['seller']))->find();
                    $content = '游客已经对订单'.$order['fuwuneirong'].'付款，请确认接待';
                    $member = M('member')->where(array('userid'=>$order['mid']))->find();
                    $this->tuisong($content,$content,$seller);
                    $this->forward($order['onum'],$order['mid'],$order['seller']);
                    $this->sendbuyline($member,$seller,$order);
                }
            }else{
                $data['trade_no'] = $trade_no;
                $data['buyer_email'] = $buyer_email;
                $data['status'] = '1';
                $data['payfs'] = '1';
                M('order')->where(array('onum'=>$onum))->save($data);

            }

        }
    }
}